#!/usr/bin/env python
# coding=utf-8
"""
@file: df_multiIndex_util.py
@contact: bianzhiwei@iyoujia.com
@time   : 2019/4/28 17:03 
@Desc   :
"""
import json
import logging
import pandas as pd
from report_system.utils import num_util
import collections


def list_to_df(data_list, columns=None):
    if isinstance(data_list, list):
        return pd.DataFrame(data_list, columns=columns)
    return None


def first_title(columns, base_name, except_names=None):
    """
    df  设置多级标题
    :param columns: df.columns
    :param base_name:  一级标题名称
    :param except_names:  期待 columns 中不包含的数据 list str
    :return:
    """
    # 将df.index 转为 list
    columns_ = list(columns)
    if not isinstance(except_names, list):
        except_names = [except_names]
    for except_name in except_names:
        if except_name and except_name != '' and except_name in columns_:
            # 去除不想要的列
            columns_.remove(except_name)
    base_names = [base_name for i in columns_]
    return [base_names, columns_]


# def Transverse_Transformation_Vertical():
def t(df: pd.DataFrame, by: str, group=None, by_value=None, v1=None, v2=None, how=None, dict_name=None, avg=None):
    """

    :param df:
    :param by:
    :param group:
    :param by_value:
    :param v1:
    :param v2:
    :param how: jia jian chen chu
    :param dict_name: jia jian chen chu
    :param avg:
    :return:
    """

    last_list = list()

    if group is None:
        logging.warning('按照 pandas.DataFrame.T 进行转换 ......')
        return df.T
    if group is not None and isinstance(group, str):
        group = [group]

    if by_value is not None and isinstance(by_value, str):
        by_value = [by_value]
    elif by_value is None and by is not None:
        by_value = df[by].unique()

    df_columns = [column for column in list(df.columns) if column not in group and column not in by]

    group_df = df[group].drop_duplicates(subset=None, keep='first', inplace=False)

    # for
    # print(group_df)
    for group_idx, group_row in group_df.iterrows():
        last_row_dict = collections.OrderedDict()
        group_dict = dict(group_row)
        temp_df = df.copy()
        for key, value in group_dict.items():
            last_row_dict[key] = value
            temp_df = temp_df[temp_df[key] == value]

        notin_df = temp_df[~temp_df[by].isin(by_value)]
        temp_df = temp_df[temp_df[by].isin(by_value)]

        for temp_idx, temp_row in temp_df.iterrows():
            temp_ti = str(temp_row[by]) + by + '-'
            for df_column in df_columns:
                temp_title = temp_ti + df_column
                if temp_title not in last_row_dict:
                    last_row_dict[temp_title] = temp_row[df_column]
                elif num_util.is_num(last_row_dict[temp_title]) and num_util.is_num(temp_row[df_column]):
                    last_row_dict[temp_title] = float(temp_row[df_column]) + float(last_row_dict[temp_title])
            #  v1=None, v2=None, how=None, dict_name=None
            if how is not None and how == 'chu':
                last_row_dict[temp_ti + dict_name] = str(round(
                    last_row_dict[temp_ti + v1] / last_row_dict[temp_ti + v2] * 100, 2)) + '%'

        for notin_idx, notin_row in notin_df.iterrows():
            for df_column in df_columns:
                temp_title = '其他-' + df_column
                val = notin_row[df_column]
                if temp_title not in last_row_dict:
                    last_row_dict[temp_title] = val
                elif num_util.is_num(last_row_dict[temp_title]) and num_util.is_num(val):
                    last_row_dict[temp_title] = float(last_row_dict[temp_title]) + float(val)
            if how is not None and how == 'chu':
                last_row_dict['其他-' + dict_name] = str(
                    round(last_row_dict['其他-' + v1] / last_row_dict['其他-' + v2] * 100, 2)) + '%'

        last_list.append(last_row_dict)
        # print(by_df)
        # print(' ---- ')
        # row_df = df[df.]
    return pd.DataFrame(last_list).reset_index()


def df_set_index(df, by):
    if isinstance(by, str):
        by = [by]
    df.set_index(by, inplace=True)
    return df


def df_group():
    """
    df 的分组求和
    grouped = lodge_df.groupby(['城市']).agg({'房屋数': 'sum', '日价': 'mean', '订单量': 'sum'})
    :return:
    """


def group_concat(data):
    data_set = [str(d) for d in set(data)]

    return ','.join(data_set)


def df_set_first_title(df, title):
    # 获取二级标题  df.columns
    title_columns = first_title(df.columns, title)
    # 设置二级标题
    df.columns = title_columns
    return df


def float_int(df):
    # 转int64
    for col in df.columns:
        df[col] = df[col].map(lambda x: int(x) if isinstance(x, int) else x)
    return df


def df_to_numeric(df):
    """
    将df转为数值型  暂时废弃
    :param df:
    :return:
    """
    # df = df.astype(float, ignore='ignore')
    print(df)
    # df = df.apply(_to_numeric, errors='ignore')
    # df = df.apply(partial(pd.to_numeric, errors='ignore'))
    # df = float_int(df)
    return df


def _to_numeric(series, errors):
    s = pd.to_numeric(series, errors=errors)
    # print(s.name,s.)
    return s


def df_reset_index(df):
    return df.reset_index()


def df_rename(df, columns_dict, inplace=True):
    """
    修改DataFrame 的列名
    :param df:
    :param columns_dict: k:原名  v:修改之后的名
    :param inplace:
    :return:
    """
    df.rename(columns=columns_dict, inplace=inplace)
    return df


def df_drop(df, by, axis=1):
    """
    :param df:
    :param by:
    :param axis: 【axis=1 为是删除列 】 【axis=0 为是删除行 】
    :return:
    """
    if isinstance(by, str):
        by = [by]
    return df.drop(by, axis=axis)


def df_sort(df, by, ascending=False):
    if isinstance(by, str):
        by = [by]
    return df.sort_values(by=by, ascending=ascending)  # by 指定列 ascending


def df_to_json(df, orient='records'):
    return json.loads(df.to_json(orient=orient))


if __name__ == '__main__':
    temp_df = pd.DataFrame([['1', None, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])
    print(temp_df)
    temp_df = temp_df.set_index(0)
    temp_df.columns = [['A', 'A', 'B', 'B'], ['a', 'b', 'c', 'd']]
    temp_df.columns = [['A', 'A', 'B', 'B'], ['a', 'b', 'c', 'd']]
    a = df_to_numeric(temp_df)
    print(a)
